import { ref, onUnmounted } from 'vue'
const mouseType = {
  mousedown: {
    0: 1,
    1: 3,
    2: 5,
    3: 7
  },
  mouseup: {
    0: 2,
    1: 4,
    2: 6,
    3: 8
  },
  mousemove: {
    0: 0
  }
}
export function useMouse() {
  const offsetX = ref(0)
  const offsetY = ref(0)
  let ele = null
  let p2p = null
  let remoteId = null
  // 发送消息
  const sendMessage = (event) => {
    offsetX.value = event.pageX
    offsetY.value = event.pageY
    const xPos = Math.floor((event.pageX * 65535) / ele.offsetWidth)
    const yPos = Math.floor((event.pageY * 65535) / ele.offsetHeight)
    const params = {
      endpointType: 1,
      events: [
        {
          eventType: 'mouse',
          timestamp: Math.floor(new Date().getTime() / 1000) + '',
          eventData: JSON.stringify({
            mask: mouseType[event.type][event.button],
            xPos,
            yPos,
            xMovement: event.movementX,
            yMovement: event.movementY
          })
        }
      ]
    }
    p2p && p2p.send(remoteId, JSON.stringify(params))
  }
  const addWheelEvent = (event) => {
    let type = null
    if (event.deltaY < 0) {
      // 滚轮向上
      type = 'mouseup'
    } else {
      // 滚轮向下
      type = 'mousedown'
    }
    sendMessage({
      ...event,
      button: 3,
      type
    })
  }
  // 添加鼠标移动事件
  const addMouseMove = (event) => {
    sendMessage(event)
  }
  // 添加鼠标按下事件
  const addMouseDown = (event) => {
    sendMessage(event)
  }
  // 添加鼠标抬起事件
  const addMouseUp = (event) => {
    sendMessage(event)
  }

  const addMouseEvent = (el, p2pObj, id) => {
    console.log('监听鼠标事件...')
    ele = el
    p2p = p2pObj
    remoteId = id

    ele.addEventListener('mousemove', addMouseMove)
    ele.addEventListener('mousedown', addMouseDown)
    ele.addEventListener('mouseup', addMouseUp)
    window.addEventListener('mousewheel', addWheelEvent)

    // 阻止鼠标右键事件
    document.oncontextmenu = (event) => {
      event.preventDefault()
    }
  }
  // 移除鼠标监听事件
  const removeMouseEvent = () => {
    ele.removeEventListener('mousemove', addMouseMove)
    ele.removeEventListener('mousedown', addMouseDown)
    ele.removeEventListener('mouseup', addMouseUp)
    window.removeEventListener('mousewheel', addWheelEvent)
  }
  onUnmounted(() => {
    try {
      removeMouseEvent()
    } catch (err) {
      console.log('remove error')
    }
  })
  return { offsetX, offsetY, addMouseEvent, removeMouseEvent }
}
